package com.dinim.test.objectlibrary;

import java.util.ArrayList;
import java.util.List;

import com.dinim.math.GeometryUtil;
import com.dinim.matrix.twodimensional.IPoint2D;
import com.dinim.object.IObject2D;
import com.dinim.object.Line2D;
import com.dinim.physics2D.ContactResolver2;



public class ObjectIntersectionResolver {

	public List getIntersections(List objects){
		
		List intersections = new ArrayList();
		ContactResolver2 cr = new ContactResolver2();
		List collidingObjects = cr.getCollidingObjects(objects);
        
        //System.out.println("colliding objects: " + collidingObjects.size());
		
		for(int i = 0; i < collidingObjects.size(); i++){
            IObject2D[] objs = (IObject2D[]) collidingObjects.get(i);
            IObject2D obj1 = objs[0];
            IObject2D obj2 = objs[1];
            List l = new ArrayList();
            l.addAll(obj1.getLines());
            l.addAll(obj2.getLines());
            //System.out.println("all lines: " + l.size());
            List collidingLines = cr.getCollidingObjects(l);
            //System.out.println("colliding lines: " + collidingLines.size());
            for(int j = 0; j < collidingLines.size(); j++){
                IObject2D[] lines = (IObject2D[])collidingLines.get(j);
                Line2D line1 = (Line2D)lines[0];
                Line2D line2 = (Line2D)lines[1];
                IPoint2D p = GeometryUtil.getIntersection(line1.getPoints()[0], line1.getPoints()[1], line2.getPoints()[0], line2.getPoints()[1]);
                if(p != null){
                    intersections.add(p);
                }
            }
        }
		return intersections;
	}
	
	public List getBBIntersections(List objects){
		
		List intersections = new ArrayList();
		ContactResolver2 cr = new ContactResolver2();
		List collidingObjects = cr.getCollidingObjects(objects);
		
		for(int i = 0; i < collidingObjects.size(); i++){
            IObject2D[] objs = (IObject2D[]) collidingObjects.get(i);
            IObject2D obj1 = objs[0];
            IObject2D obj2 = objs[1];
            List l = new ArrayList();
            l.addAll(obj1.getLines());
            l.addAll(obj2.getLines());
            List collidingLines = cr.getCollidingObjects(l);
            for(int j = 0; j < collidingLines.size(); j++){
                IObject2D[] lines = (IObject2D[])collidingLines.get(j);
                Line2D line1 = (Line2D)lines[0];
                Line2D line2 = (Line2D)lines[1];
                intersections.add(line1.getBoundingBox());
                intersections.add(line2.getBoundingBox());
            }
        }
		return intersections;
	}
	
}
